import { getPage } from '../../utils/config';
import api from '../../utils/api';
import { http, $empty, $toast, storage, Validate } from '../../utils/utils';
import wxApi from '../../utils/wxApi';
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        regionInfo: [],
        pickerArea: true,
        areaShow: false,
        pickerValue: '110101',
        areaList: {
            province_list: {},
            city_list: {},
            county_list: {},
        },
        addressForm: {
            consignee: '',
            phoneNumber: '',
            location: '',
            address: '',
            isDefault: false,
            locationId: [],
        }
    },

    toggle(type) {
        this.setData({
            [type]: !this.data[type]
        });
    },

    /**
     * 城市选择open || close
     */
    pickerAreaTap() {
        this.toggle('areaShow');
    },
    
    /**
     * 确定选择城市
     */
    pickerAreaConfirm(e) {
        const { index, values } = e.detail;
        const { regionInfo } = this.data;
        const provice = regionInfo[index[0]];
        const city = provice.list[index[1]];
        const county = city.list[index[2]];
        this.setData({
            locationError: '',
            'addressForm.location': `${provice.name} ${city.name} ${county.name}`,
            'addressForm.locationId': [provice.id, city.id, county.id],
        });
        this.pickerAreaTap();
    },

    /**
     * 收货人
     */
    consigneeInput(e) {
        this.setData({
            consigneeError: '',
            'addressForm.consignee': $empty(e.detail)
        })
    },

    /**
     * 手机号码
     */
    phoneNumberInput(e) {
        this.setData({
            phoneNumberError: '',
            'addressForm.phoneNumber': $empty(e.detail)
        })
    },

    /**
     * 所在地址
     */
    locationInput(e) {
        this.setData({
            locationError: '',
            'addressForm.location': e.detail
        })
    },

    /**
     * 详细地址
     */
    addressInput(e) {
        this.setData({
            addressError: '',
            'addressForm.address': e.detail
        })
    },

    /**
     * 是否开启默认收货
     */
    defaultChange(e) {
        wx.vibrateShort();
        this.setData({
            'addressForm.isDefault': e.detail
        });
    },
 
    /**
     * 提交保存
     */
    addressForm(e) {
        Validate.check(this, this.addressValidate, e.detail.value, (res) => {
            if(res){
                const data = this.data;
                const { consignee, phoneNumber, locationId, address, isDefault } = data.addressForm;
                const params = {
                    action: 'address-save',
                    name: consignee,
                    mobile: phoneNumber,
                    province_id: locationId[0],
                    city_id: locationId[1],
                    district_id: locationId[2],
                    detail: address,
                    userid: data.userId,
                    is_default: Number(isDefault),
                }
                //修改地址
                if (this.mode) {
                    params.address_id = data.addressInfo.address_id;
                }

                http.post(api.default, {
                    data: params
                }).then((res) => {
                    $toast('修改成功', {
                        icon: 'success'
                    });
                    const pages = getCurrentPages()[getCurrentPages().length - 2];
                    //返回上一页
                    wx.navigateBack({
                        delta: 1,
                        success() {
                            if(pages !== undefined || pages !== null){
                                pages.onLoad();
                            }
                        },
                    });
                });
            }
        });
    },

    /**
     * 获取地区
     */
    getRegionInfo() {
        return new Promise((resolve) => {
            storage.get('regionInfo').then((res) => {
                this.setData({ regionInfo: res, pickerArea: false });
                resolve(res);
            }).catch((res) => {
                http.get(api.default, {
                    data: {
                        action: 'district'
                    }
                }, false).then((res) => {
                    const { data } = res.data;
                    this.setData({ regionInfo: data, pickerArea: false });
                    storage.set('regionInfo', data);
                    resolve(data);
                });
            });
        });
    },

    /**
     * 城市数据格式转换
     * @整体是一个 Object，包含 province_list, city_list, county_list 三个 key。
     * @每项以省市区编码作为 key，省市区名字作为 value。编码为 6 位数字，前两位代表省份，中间两位代表城市，后两位代表区县，以 0 补足 6 位。如北京编码为 11，以零补足 6 位，为 110000。
     */
    formatArea() {
        const { regionInfo, areaList } = this.data;
        let { province_list, city_list, county_list } = areaList;

        //一级 省份
        regionInfo.forEach((parentsItem, parentsIndex) => {
            parentsIndex = (parentsIndex + 11).toString();
            let parentsCode = parentsIndex;
            let parentsLength = parentsIndex.length;
            if(parentsLength < 6){
                for (let i = 0; i < 6 - parentsLength; i++){
                    parentsCode = parentsCode + `0`;
                }
            }

            //二级 城市
            if (parentsItem.list.length){
                parentsItem.list.forEach((parentItem, parentIndex) => {
                    //从1开始
                    parentIndex = (parentIndex + 1).toString();
                    if(parentIndex < 10){
                        parentIndex = `0` + parentIndex;
                    }
                    parentIndex = parentsIndex + parentIndex;
                    let parentCode = parentIndex;
                    let parentLength = parentIndex.length;
                    if(parentLength < 6) {
                        for (let i = 0; i < 6 - parentLength; i++) {
                            parentCode = parentCode + `0`;
                        }
                    }
                    city_list[parentCode] = parentItem.name;

                    //三级 区
                    if (parentItem.list.length){
                        parentItem.list.forEach((item, index) => {
                            //从1开始
                            index = (index + 1).toString();
                            if (index < 10) {
                                index = `0` + index;
                            }
                            index = parentIndex + index;
                            let code = index;
                            let length = index.length;
                            if (length < 6) {
                                for (let i = 0; i < 6 - length; i++) {
                                    code = code + `0`;
                                }
                            }
                            county_list[code] = item.name
                        });
                    }
                });
            }
            province_list[parentsCode] = parentsItem.name;
        });
        
        this.setData({ areaList });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        //默认 添加地址
        this.mode = 0;
        //获取上一个页面数据
        const { data } = getCurrentPages()[getCurrentPages().length - 2];
        //获取用户id
        this.setData({
            userId: data.userId
        });
        //获取携带参数
        if(Object.keys(options).length){
            //修改地址
            this.mode = 1;
            //修改导航栏标题
            wx.setNavigationBarTitle({
                title: '修改收货地址',
            });
            //需要修改的收货地址
            const { id } = options;
            //获取当前收货地址
            let { consignee, phoneNumber, location, address, isDefault, locationId } = this.data.addressForm;

            data.addressInfo.forEach((item) => {
                if(item.address_id == id){
                    const { province, district, city } = item.zonedata;
                    consignee = item.consignee;
                    phoneNumber = item.mobile;
                    location = `${province.name} ${city.name} ${district.name}`
                    address = item.address;
                    isDefault = item.is_default;
                    locationId = [province.id, city.id, district.id];

                    this.setData({
                        addressInfo: item,
                        addressForm: { consignee, phoneNumber, location, address, isDefault, locationId }
                    });
                }
            });
        };

        /**
         * 获取地区
         */
        this.getRegionInfo().then((res) => {
            //地区格式化
            this.formatArea();
            //如果修改地址
            if(this.mode){
                const data = this.data;
                const { district } = data.addressInfo.zonedata;
                const { county_list } = data.areaList;
                Object.entries(county_list).map((key) => {
                    if(district.name == key[1]){
                        this.setData({
                            pickerValue: key[0],
                        })
                    }
                })
            }
        });
        
        /**
         * 收货地址保存
         */
        Validate.rules('#consignee,#phoneNumber,#location,#address', (res) => {
            this.addressValidate = res;
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    }
})